package de.dhe.client;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.message.BasicNameValuePair;

import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;

import de.dhe.client.domain.Response;

public class AlbumCtrl extends AbstractCltr {

	public AlbumCtrl(HttpClient client) {
		super(client);

	}

	public Response listAblum(String uuid) {

		HttpPost post = new HttpPost(REST_URL);
		try {
			List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
			nameValuePairs.add(new BasicNameValuePair("tag", "listalbum"));

			nameValuePairs.add(new BasicNameValuePair("uuid", uuid));

			post.setEntity(new UrlEncodedFormEntity(nameValuePairs));

			HttpResponse response = client.execute(post);
			int statusCode = response.getStatusLine().getStatusCode();

			System.out.println("Response statsu" + statusCode);
			BufferedReader rd = new BufferedReader(new InputStreamReader(
					response.getEntity().getContent()));
			String line = "";
			StringBuffer bu = new StringBuffer();
			while ((line = rd.readLine()) != null) {
				System.out.println(line);
				bu.append(line);
			}

			ObjectMapper mapper = new ObjectMapper();
			mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES,
					false);
			Response json = mapper.readValue(bu.toString(), Response.class);
			return json;
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

	public Response createAblum(String uuid, String albumName) {

		HttpPost post = new HttpPost(REST_URL);
		try {
			List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
			nameValuePairs.add(new BasicNameValuePair("tag", "newalbum"));

			nameValuePairs.add(new BasicNameValuePair("name", albumName));
			nameValuePairs.add(new BasicNameValuePair("uuid", uuid));

			post.setEntity(new UrlEncodedFormEntity(nameValuePairs));

			HttpResponse response = client.execute(post);
			int statusCode = response.getStatusLine().getStatusCode();

			System.out.println("Response status create Album " + statusCode);
			BufferedReader rd = new BufferedReader(new InputStreamReader(
					response.getEntity().getContent()));
			String line = "";
			StringBuffer bu = new StringBuffer();
			while ((line = rd.readLine()) != null) {
				System.out.println(line);
				bu.append(line);
			}

			ObjectMapper mapper = new ObjectMapper();
			Response json = mapper.readValue(bu.toString(), Response.class);

			return json;
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;

	}

}
